﻿using MQ.Core.Util;
using System;
using System.Collections.Generic;
using System.Linq;

namespace MQ.Core.Model
{
    public class TreeModel
    {
        public long? id { set; get; }
        public string code { set; get; }
        public string pcode { set; get; }

        public long? pid { set; get; }

        public string text { set; get; }
        public string label { get { return text; } }

        public string value { set; get; }

        public List<TreeModel> children { set; get; }
    }

    public static class TreeModelExtention
    {
        /// <summary>
        /// TreeModel to tree
        /// type:code-use code、id-user id
        /// </summary>
        /// <param name="list"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static List<TreeModel> ToTree(this List<TreeModel> list,string type="code")
        {
            Func<string, List<TreeModel>> func = null;
            List<TreeModel> result = new List<TreeModel>();
            func = new Func<string, List<TreeModel>>(x => {
                List<TreeModel> a = null;
                if (type == "code")
                {
                    a = list.Where(m => m.pcode == x).ToList();
                }
                else
                {
                    a = list.Where(m => m.id+"" == x).ToList();
                }
                foreach(var item in a)
                {
                    //var tree = new TreeModel() { code=item.code,pcode=item.pcode,id=item.id,pid=item.pid};
                    //tree.children = new List<TreeModel>();
                    item.children = new List<TreeModel>();
                    if (type=="code")
                    {
                        item.children = func(item.code);
                    }
                    else
                    {
                        item.children = func(item.id+"");
                    }
                }
                return a;
            });
            return func("0");
        }
    }
}
